﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using PortalCurriculo.Util.CustomControls.ListViewObjects;

namespace PortalCurriculo.Util.CustomControls
{
    public class AutoListView : Control
    {
        private static ListView ListView { get; set; }
        public object DataSource { get; set; }
        public TableStructure TableStructure { get; set; }
        public string EmptyDataMessage { private get; set; }
        
        public IList<ListViewDataItem> Items {
            get
            {
               return ListView.Items;
                //if (DataSource == null) return null;

                //var list = new List<ListViewDataItem>();

                //if (!(DataSource is IEnumerable))
                //{
                //    list.Add(new ListViewDataItem(0,0){DataItem = DataSource});
                //    return list;
                //}

                //var dataSourceList = (IEnumerable) DataSource;
                //var index = 0;

                //foreach (var item in dataSourceList)
                //{
                //    list.Add(new ListViewDataItem(index, index) { DataItem = item });
                //    index++;
                //}

                //return list;
            }
        }

        public AutoListView()
        {
            ListView = new ListView();
        }

        public void DataBind<T>(List<Field> fields)
        {
            DataBind<T>(fields, null);
        }

        public void DataBind<T>(List<Field> fields, List<ActionControl> actionControls)
        {
            if (fields != null)
            {
                ListView.ItemPlaceholderID = "phItem";

                if (DataSource != null && ((List<T>)DataSource).Count > 0)
                {
                    ListView.LayoutTemplate = new LayoutTemplate(fields, TableStructure);
                    ListView.ItemTemplate = new ItemTemplate<T>(fields, DataSource, actionControls);
                }
                else
                    if (EmptyDataMessage != null)
                        ListView.EmptyDataTemplate = new EmptyDataTemplate(EmptyDataMessage);    
            }

            ListView.DataSource = DataSource;
            ListView.DataBind();

            Controls.Add(ListView);
        }
    }
}